package com.jiyun.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jiyun.common.RedisContact;
import com.jiyun.mapper.MsgMapper;
import com.jiyun.mapper.UserMapper;
import com.jiyun.pojo.Msg;
import com.jiyun.pojo.User;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@Service
public class UserService {


    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    MsgMapper msgMapper;

    @Autowired
    UserMapper userMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;

    public String sendMsg(Msg msg) {
        msg.setCreateTime(LocalDateTime.now());
        msgMapper.insert(msg);
        // 存放消息本身
        redisTemplate.boundHashOps(RedisContact.HASHMSG).put(msg.getId()+"",msg.getName());

        // 通过消息的用户等级，可以得到对应的用户信息
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getUserLevel,msg.getUserLevel());
        List<User> userList = userMapper.selectList(qw);
        for (User user : userList) {
            redisTemplate.boundListOps(RedisContact.LISTMSG+":"+user.getId()).leftPush(msg.getId()+"");
        }

        // 存放消息的有效期
        // 时间格式：date 年月日 time 时分秒 datetime 时间戳 1970-现在的所有的秒的总和
        ZoneId zone = ZoneId.systemDefault();
        long l = msg.getExpireTime().atZone(zone).toInstant().toEpochMilli();
        redisTemplate.boundZSetOps(RedisContact.ZSETMSG).add(msg.getId()+"",l);

        // 重要消息，需要通过rabbitMQ进行消息的发送
        if (msg.getType().equals("1")) {
            String phoneNum="";
            for (User user : userList) {
                phoneNum=phoneNum+"-"+user.getPhone();
            }

            rabbitTemplate.convertAndSend("xxxx","xxxx",phoneNum);
        }

        return "消息发送成功！";
    }

    public String findMsg(User user) {
        // 根据账号密码，查询用户是否存在
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getUsername,user.getUsername());
        qw.eq(User::getPassword,user.getPassword());
        User userSQL = userMapper.selectOne(qw);
        if(userSQL==null){
            return "账号或密码错误！";
        }

        String allMsg = "";
        // 每个用户对应的消息id
        List<String> list = redisTemplate.boundListOps(RedisContact.LISTMSG + ":" + userSQL.getId()).range(0, -1);
        for (String id : list) {
            String msg = (String)redisTemplate.boundHashOps(RedisContact.HASHMSG).get(id);
            if(msg==null){
                // 消息已过期，被删除
                redisTemplate.boundListOps(RedisContact.LISTMSG + ":" + userSQL.getId()).remove(0,id);
            }else{
                allMsg=allMsg+"\n"+msg;
            }

        }


        return allMsg;
    }
}
